//
//  FarmSupermarketViewController.m
//  PeopleStreet
//
//  Created by 刘建峰 on 16/6/27.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "FarmSupermarketViewController.h"
#import "FarmSupplyTableViewCell.h"
#import "SupermarketFarmTableViewCell.h"
#import "SupermarketDetailViewController.h"
#import "FarmDetailViewController.h"
static NSString * farmcellIndentfier = @"FarmSupplyTableViewCell";
static NSString * supercellIndentfier = @"SupermarketFarmTableViewCell";
@interface FarmSupermarketViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIView *typeView;
@property (weak, nonatomic) IBOutlet UIButton *typeButton;
@property (weak, nonatomic) IBOutlet UILabel *backLabel;
@property (weak, nonatomic) IBOutlet UILabel *frontLabel;
@property(nonatomic,strong)NSMutableArray * listArray;
@end

@implementation FarmSupermarketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _listArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.typeView];

    [self.tableView registerNib:[UINib nibWithNibName:farmcellIndentfier bundle:nil] forCellReuseIdentifier:farmcellIndentfier];
    
    [self.tableView registerNib:[UINib nibWithNibName:supercellIndentfier bundle:nil] forCellReuseIdentifier:supercellIndentfier];
    
    _typeView.layer.masksToBounds = YES;
    _typeView.layer.cornerRadius = 13*VerticalRatio();
    _frontLabel.layer.masksToBounds = YES;
    _frontLabel.layer.cornerRadius = 13*VerticalRatio();
    
    
 
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            if (_typeButton.selected) {
             [self getSupermarketList];
            }else{
                [self getFarmList];
            }
           
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.listArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            if (_typeButton.selected) {
                [self getSupermarketList];
            }else{
                [self getFarmList];
            }
        });
    }
    
}

#pragma mark === 获取求购列表
- (void)getSupermarketList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallMarketDemand withHttpType:@"POST" withTag:SX_SX_queryMallMarketDemand];

}

#pragma mark === 获取供应列表
- (void)getFarmList{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallMarketSupply withHttpType:@"POST" withTag:SX_SX_queryMallMarketSupply];
}

#pragma mark == 发布

- (IBAction)post:(id)sender {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"FarmSupermarketStoryboard" bundle:nil];
        UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PostSupermarketOrFarm"];
        [self.navigationController  pushViewController:page animated:YES];
}


- (IBAction)changeType:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        
        _frontLabel.text = @"求购";
        _backLabel.textAlignment = NSTextAlignmentLeft;
        _backLabel.text = @"供应";
        [UIView animateWithDuration:0.2 animations:^{
            _frontLabel.frame = flexibleFrame(CGRectMake(80, 0, 80, 26), NO);
        }];
    }else{
        _frontLabel.text = @"供应";
        _backLabel.textAlignment = NSTextAlignmentRight;
        _backLabel.text = @"求购";
        [UIView animateWithDuration:0.2 animations:^{
            _frontLabel.frame = flexibleFrame(CGRectMake(0, 0, 80, 26), NO);
        }];
        
    }
    [_listArray removeAllObjects];
    _pageNO = 1;
    [self addRefreshing];
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_typeButton.selected) {
        return 83*VerticalRatio();
    }else{
        return 90*VerticalRatio();
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_typeButton.selected) {
        SupermarketFarmTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:supercellIndentfier];
        if (cell == nil) {
            cell= [[SupermarketFarmTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:supercellIndentfier];
        }
        
        NSDictionary * dic = _listArray[indexPath.row];

        cell.superTitle.text  = [Common stringFromData:dic[@"mmdeName"]];
        cell.superDetail.text  = [Common stringFromData:dic[@"mmdeContent"]];
        cell.time.text = [Common stringFromData:dic[@"mmdeCreateTime"]];
        if ([Common stringFromData:dic[@"mmdeCreateTime"] ].length>0) {
            cell.time.text = [Common updateTimeForData:[Common stringFromData:dic[@"mmdeCreateTime"] ]];
        }
        
        return cell;
    }else{
        FarmSupplyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:farmcellIndentfier];
        if (cell == nil) {
            cell= [[FarmSupplyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:farmcellIndentfier];
        }
        NSDictionary * dic = _listArray[indexPath.row];
        
    NSString * image = [Common stringFromData:dic[@"mmsuImageUrl"]];
        if (image.length>0) {
            [cell.farmImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }
        cell.farmTitle.text  = [Common stringFromData:dic[@"mmsuName"]];
        cell.farmDetail.text  = [Common stringFromData:dic[@"mmsuContent"]];
        if ([Common stringFromData:dic[@"mmsuCreateTime"] ].length>0) {
            cell.time.text = [Common updateTimeForData:[Common stringFromData:dic[@"mmsuCreateTime"] ]];
        }
         return cell;
    }
 
    return nil;
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_typeButton.selected) {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"FarmSupermarketStoryboard" bundle:nil];
        SupermarketDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SupermarketDetail"];
        page.superId = _listArray[indexPath.row][@"mmdeId"];
        [self.navigationController  pushViewController:page animated:YES];
    }else{
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"FarmSupermarketStoryboard" bundle:nil];
        FarmDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"FarmDetail"];
        page.farmId = _listArray[indexPath.row][@"mmsuId"];
        [self.navigationController  pushViewController:page animated:YES];
    }
  
}



#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==SX_SX_queryMallMarketSupply||tag==SX_SX_queryMallMarketDemand) {
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.listArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.listArray addObject:entity];
                }
            _tableView.dataSource = self;
            _tableView.delegate = self;
            [_tableView reloadData];
        });
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    //
    [self dismissWaitDialog];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
